<template>
  <el-dialog :visible.sync="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false"
    :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()"
      :label-width="$i18n.locale === 'en-US' ? '150px' : '110px'">
      <el-form-item label="客户选择" prop="customerId">
        <el-select style="width: 100%" v-model="dataForm.customerId" filterable clearable placeholder="请选择客户">
          <el-option v-for="item in customerInfoList" :key="item.id" :label="item.companyName" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="服务项目" prop="serviceItem">
        <el-input v-model="dataForm.serviceItem" placeholder="服务项目"></el-input>
      </el-form-item>
      <el-form-item label="订单成本" prop="costAmount">
        <el-input-number style="width: 100%" v-model="dataForm.costAmount" :precision="2" :step="0.1" :max="10000000" placeholder="订单成本"></el-input-number>
      </el-form-item>
      <el-form-item label="订单总金额" prop="totalAmount">
        <el-input-number style="width: 100%" v-model="dataForm.totalAmount" :precision="2" :step="0.1" :max="10000000" placeholder="订单总金额"></el-input-number>
      </el-form-item>
      <el-form-item label="介绍人" prop="introducer">
        <el-input v-model="dataForm.introducer" placeholder="介绍人"></el-input>
      </el-form-item>
      <el-form-item label="签约日期" prop="signedDate">
        <el-date-picker
          v-model="dataForm.signedDate"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="签约日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="合同情况">
        <el-radio-group v-model="contractFlag" @change="changeContractFlag">
          <el-radio-button :label="true">已签合同</el-radio-button>
          <el-radio-button :label="false">未签合同</el-radio-button>
        </el-radio-group>  
      </el-form-item>
      <el-form-item v-show="contractFlag" label="合同编号" prop="contractNumber">
        <el-input v-model="dataForm.contractNumber" placeholder="合同编号"></el-input>
      </el-form-item>
      <el-form-item v-show="contractFlag" label="上传合同图片" prop="imageDataList">
        <el-upload
          class="upload-demo"
          :action="uploadUrl"
          :headers="headers"
          :show-file-list="true"
          :multiple="true"
          :on-success="imageHandleAvatarSuccess"
          :on-change="imageHandleChange"
          :on-remove="imageRemove"
          :before-upload="imageOnBeforeUpload"
          :file-list="imageList">
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item v-show="contractFlag" label="上传合同文件" prop="fileDataList">
        <el-upload
          class="upload-demo"
          :action="uploadUrl"
          :headers="headers"
          :show-file-list="true"
          :multiple="true"
          :on-success="fileHandleAvatarSuccess"
          :on-change="fileHandleChange"
          :on-remove="fileRemove"
          :before-upload="fileOnBeforeUpload"
          :file-list="dataFileList">
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>
      <!-- 未签合同展示内容 -->
      <el-form-item v-show="!contractFlag" label="上传报价图片" prop="amountImagePathList">
        <el-upload
          class="upload-demo"
          :action="uploadUrl"
          :headers="headers"
          :show-file-list="true"
          :multiple="true"
          :on-success="amountImageHandleAvatarSuccess"
          :on-change="amountImageHandleChange"
          :on-remove="amountImageRemove"
          :before-upload="amountImageOnBeforeUpload"
          :file-list="amountImageList">
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{
        $t("confirm")
        }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import Cookies from 'js-cookie'
import debounce from "lodash/debounce";
export default {
  data() {
    return {
      uploadUrl: window.SITE_CONFIG['apiURL'] + '/order/order/upload/files',
      headers: { token: Cookies.get('token') },
      visible: false,
      dataForm: {
        id: "",
        customerId: "",
        serviceItem: "",
        costAmount: "",
        totalAmount: "",
        introducer: "",
        introducerPhone: "",
        contractId: "",
        contractNumber: "",
        signedDate: "",
        imageDataList: [],
        fileDataList: [],
        amountImagePathList: [],
        contractFlag: true
      },
      customerInfoList: [],
      imageList: [],
      pushImageList: [],
      dataFileList: [],
      pushDataFileList: [],
      amountImageList: [],
      pushAmountImageList: [],
      contractFlag: true
    };
  },
  computed: {
    dataRule() {
      const rules = {
        customerId: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        serviceItem: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        costAmount: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        totalAmount: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        introducer: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        signedDate: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ]
      };
      if(this.contractFlag) {
        rules.imageDataList = [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ];
      } else {
        rules.amountImagePathList = [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ];
      }
      return rules;
    },
  },
  methods: {
    init() {
      this.imageList = []
      this.pushImageList = []
      this.dataFileList = []
      this.pushDataFileList =[]
      this.amountImageList = []
      this.pushAmountImageList =[]
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.id) {
          this.getInfo();
        }
      });
      this.getAllCustomers();
    },
    // 上传格式做限制
    imageOnBeforeUpload(file) {
      var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      const extension = testmsg === "jpg" || testmsg === "png" || testmsg === "jpeg" || testmsg === "JPEG";
      if (!extension) {
        setTimeout(() => {
          this.$message({
            message: `文件"${file.name}"只能上传jpg、jpeg、JPEG格式!`,
            type: "warning"
          });
        })
        this.imageList =[]
      }
      return extension;
    },
    // 上传格式做限制
    fileOnBeforeUpload(file) {
      var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      const extension = testmsg === "pdf" || testmsg === "PDF" || testmsg === "doc" || testmsg === "docs";
      if (!extension) {
        setTimeout(() => {
          this.$message({
            message: `文件"${file.name}"只能上传pdf、doc、docs格式!`,
            type: "warning"
          });
        })
        this.dataFileList = []
      }
      return extension;
    },
    // 上传格式做限制
    amountImageOnBeforeUpload(file) {
      var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      const extension = testmsg === "jpg" || testmsg === "png" || testmsg === "jpeg" || testmsg === "JPEG";
      if (!extension) {
        setTimeout(() => {
          this.$message({
            message: `文件"${file.name}"只能上传jpg、jpeg、JPEG格式!`,
            type: "warning"
          });
        })
        this.amountImageList =[]
      }
      return extension;
    },
    imageHandleChange(file, imageList) {
      this.imageList = imageList.slice(-3);
    },
    imageHandleAvatarSuccess(res, file) {
      this.pushImageList.push(res.data);
      this.dataForm.imageDataList = this.pushImageList
    },
    imageRemove(file, imageList) {
      console.log(file)
      console.log(imageList)
      this.dataForm.imageDataList = imageList
    },
    fileHandleChange(file, fileList) {
      this.dataFileList = fileList.slice(-3);
    },
    fileHandleAvatarSuccess(res, file) {
      this.pushDataFileList.push(res.data);
      this.dataForm.fileDataList = this.pushDataFileList
    },
    fileRemove(file, fileList) {
      this.dataForm.fileDataList = fileList
    },
    amountImageHandleChange(file, fileList) {
      this.amountImageList = fileList.slice(-3);
    },
    amountImageHandleAvatarSuccess(res, file) {
      this.pushAmountImageList.push(res.data);
      this.dataForm.amountImagePathList = this.pushAmountImageList
    },
    amountImageRemove(file, fileList) {
      this.dataForm.amountImagePathList = fileList
    },
    // 改变合同情况
    changeContractFlag(val) {
      console.log('改变合同情况', val)
    },
    // 获取所有的客户信息
    getAllCustomers() {
      console.log('getAllCustomers')
      this.$http.get("/customer/customerinfo/list").then(({ data }) => {
        this.customerInfoList = data.data;
      });
    },
    // 获取信息
    getInfo() {
      console.log('getInfo')
      this.$http
        .get(`/order/order/${this.dataForm.id}`)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          this.dataForm = {
            ...this.dataForm,
            ...res.data,
          };
          if (this.dataForm.imageDataList != null) {
            this.imageList = this.dataForm.imageDataList
          }
          if (this.dataForm.fileDataList != null) {
            this.dataFileList = this.dataForm.fileDataList
          }
          this.contractFlag = this.dataForm.contractFlag
        })
        .catch(() => { });
    },
    // 表单提交
    dataFormSubmitHandle: debounce(
      function () {
        this.$refs["dataForm"].validate((valid) => {
          if (!valid) {
            return false;
          }
          this.$http[!this.dataForm.id ? "post" : "put"](
            "/order/order",
            this.dataForm
          )
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg);
              }
              this.$message({
                message: this.$t("prompt.success"),
                type: "success",
                duration: 500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
            })
            .catch(() => { });
        });
      },
      1000,
      { leading: true, trailing: false }
    ),
  },
};
</script>
